﻿using Shop.Model.DB;
using Shop.RemoteModel;
using Shop.RemoteModel.PageTemplate.Model;
using Shop.Repository.LinqHelper;
using WeDonekRpc.Client;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.Model;
using WeDonekRpc.SqlSugar;

namespace Shop.Repository.lmpl
{
    internal class PageTemplateRepository : ShopBaseRepository<DBPageTemplate, long>, IPageTemplateRepository
    {
        public PageTemplateRepository ( ISqlClientFactory factory ) : base(factory)
        {
        }
        public Result[] Query<Result> ( PageTemplateQuery query, IBasicPage paging, out int count ) where Result : class, new()
        {
            paging.InitOrderBy("Id", true);
            return base.Query<Result>(query.ToWhere(), paging, out count);
        }
        public long Add ( PageTemplateAdd add )
        {
            DBPageTemplate data = add.ConvertMap<PageTemplateAdd, DBPageTemplate>();
            data.AddTime = DateTime.Now;
            data.EditTime = DateTime.Now;
            data.Status = PageStatus.起草;
            data.Id = IdentityHelper.CreateId();
            base.Insert(data);
            return data.Id;
        }

        public bool Enable ( DBPageTemplate source, long stopId )
        {
            if ( stopId == 0 )
            {
                return base.Update(new DBPageTemplate
                {
                    Status = PageStatus.启用,
                    PublicTime = DateTime.Now
                }, a => a.Id == source.Id && a.Status == source.Status);
            }
            using ( ILocalTransaction tran = base.ApplyTran() )
            {
                if ( !base.Update(new DBPageTemplate
                {
                    Status = PageStatus.启用,
                    PublicTime = DateTime.Now
                }, a => a.Id == source.Id && a.Status == source.Status) )
                {
                    return false;
                }
                if ( !base.Update(a => a.Status == PageStatus.停用, a => a.Id == stopId) )
                {
                    return false;
                }
                tran.Commit();
                return true;
            }
        }
    }
}
